//
//  AddCarViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/13.
//

#import "AddCarViewController.h"
#import "CyCStandardCell.h"
#import "CycSwitchCell.h"
#import "CycBLEManager.h"
#import "CycCarModel.h"
#import "TestViewController.h"
#import "DeviceRequest.h"
#import "MineRequest.h"
#import "AppDelegate.h"
#import "BaseNavigationController.h"
#import "BaseTabBarController.h"
#import "Cycling-Swift.h"


@interface AddCarViewController ()<UITableViewDataSource , UITableViewDelegate>

@property (nonatomic , strong)UITableView *tableView;
@property (nonatomic , strong)UIButton *skipBtn;
@property (nonatomic , strong) NSMutableArray *scanDevices; // 搜索到的设备
@property (nonatomic , strong) NSArray *userDevices; // 连接过的设备
@property (nonatomic , assign) BOOL isHiddle;

@end

@implementation AddCarViewController

- (NSMutableArray *)scanDevices {
    if(!_scanDevices){
        _scanDevices = [NSMutableArray arrayWithCapacity:1];
    }
    return _scanDevices;
}

-(UIButton *)skipBtn {
    if (!_skipBtn) {
        _skipBtn = [[UIButton alloc] init];
        [_skipBtn setTitle:CycLocalizedString(@"Skip>>", @"跳过 >>") forState:(UIControlStateNormal)];
        _skipBtn.backgroundColor = COLOR_TOPIC_SELECT;
        _skipBtn.titleLabel.font = FONT_BODY_16;
        _skipBtn.titleLabel.textColor = COLOR_WHITE;
        _skipBtn.layer.cornerRadius = 30;
        _skipBtn.layer.masksToBounds = YES;
    }
    return _skipBtn;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - NavigationBarHeight)style:(UITableViewStyleGrouped)];
        [_tableView registerClass:[CyCStandardCell class] forCellReuseIdentifier:@"CyCStandardCell"];
        [_tableView registerClass:[CycSwitchCell class] forCellReuseIdentifier:@"CycSwitchCell"];
        _tableView.backgroundColor = COLOR_APP_BACKGROUND;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = HEIGHT_CELL48;
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [[CycBLEManager sharedManager] stopScan];
}
- (void) enterBackground {
    
}
    
- (void) enterForeground {
    [self.tableView reloadData];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = CycLocalizedString(@"Add bike", @"添加设备");
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(enterForeground)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];

    [self.view addSubview:self.tableView];
    
    if (self.isFirst) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 80)];
        [footView addSubview:self.skipBtn];
        [self.skipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(footView).offset(-30);
            make.left.equalTo(footView).offset(30);
            make.top.equalTo(footView).offset(10);
            make.height.mas_equalTo(60);
        }];
        [self.skipBtn addTarget:self action:@selector(skipBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
        self.tableView.tableFooterView = footView;
    }
     
    [[CycBLEManager sharedManager] startScanWithSuccess:^(NSArray<CBPeripheral *> *peripherals) {
        NSLog(@"-=-==============%@",peripherals);
        self.scanDevices = [peripherals copy];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"====================%@",error);
    }];
    self.isHiddle = YES;
    [self getDeviceList];
}

- (void)skipBtnAction {
    appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[BaseTabBarController alloc] init]];
    [appDelegate.window makeKeyAndVisible];
    
    [self requestHealthAppAuthorizationOnComplete:^(BOOL granted, BOOL shouldOpenHealthApp) {
        if(shouldOpenHealthApp) {
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"x-apple-health://app/"]];
            [self requestHealthAppAuthorizationOnComplete:^(BOOL granted, BOOL shouldOpenHealthApp) {
                if(shouldOpenHealthApp) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"x-apple-health://app/"] options:@{} completionHandler:^(BOOL success) {
                        
                    }];
                }
            }];
        }
    }];

}

- (void)openSetting {
    NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];

    if ([[UIApplication sharedApplication] canOpenURL:url])
    {
       [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)getDeviceList {
    [MineRequest getUserDevices:1 result:^(NSArray<DeviceModel *> *list) {
        NSLog(@"%@",list);
        self.userDevices = list;
        [self.tableView reloadData];
    }];
}

#pragma mark ==== datasource代理
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 2){
        if(!self.isHiddle){
            return CGFLOAT_MIN;
        }
    }
    return 64;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(section == 3){
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 60)];
        UILabel *titleLB = [[UILabel alloc] initWithFrame:CGRectMake(MARGIN_MAX, 20, SCREEN_W, 30)];
        titleLB.font = FONT_PRIMARY_TITLE;
        titleLB.text = CycLocalizedString(@"Search results", @"搜索结果");
        titleLB.textColor = COLOR_BLACK;
        [header addSubview:titleLB];
        
        return header;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 3){
        return 60;
    }
    return CGFLOAT_MIN;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0 || section == 1){
        return 1;
    }
    if(section == 2){
        return !self.isHiddle ? 0 : self.userDevices.count;
    }

    return self.scanDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 || indexPath.section == 1) {
        CycSwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CycSwitchCell" forIndexPath:indexPath];
        cell.backgroundColor = COLOR_APP_BACKGROUND;
        cell.titleLB.font = FONT_PRIMARY_TITLE;
        cell.titleLB.textColor = COLOR_BLACK;
        cell.titleLB.text = indexPath.section == 0 ? CycLocalizedString(@"Blue tooth", @"蓝牙") : CycLocalizedString(@"Bikes connected", @"已添加设备");
        if(indexPath.section == 0){
            [cell.cellsSwitch setOn4UI:[CycBLEManager sharedManager].state != CYCBLEManagerStateUnavailable animated:YES];
        }
        if(indexPath.section == 1){
            [cell.cellsSwitch setOn4UI:self.isHiddle animated:YES];
        }
        cell.block = ^(BOOL state) {
            if (indexPath.section == 0) {
                [self openSetting];
            }else {
                self.isHiddle = state;
                [self.tableView reloadData];
            }
        };
        return cell;
    }else {
        CyCStandardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CyCStandardCell" forIndexPath:indexPath];
        [cell setCurrentIndex:0 cellCount:1];
        cell.cellType = CycStandardCellTypeTitle;
        cell.titleLB.font = FONT_PRIMARY_TITLE;
        cell.titleLB.textColor = COLOR_NOT_SELECT;
        cell.subTitleLB.font = FONT_PRIMARY_TITLE;
        cell.subTitleLB.textColor = COLOR_TOPIC_SELECT;
        NSString *connectedName = [CycBLEManager sharedManager].connectedCar.bleName;

        if(indexPath.section == 3){
            CBPeripheral *peripherals = self.scanDevices[indexPath.row];
            cell.titleLB.text = peripherals.name;
            if([connectedName isEqualToString:peripherals.name]){
                cell.subTitleLB.textColor = COLOR_NOT_SELECT;
                cell.subTitleLB.text = CycLocalizedString(@"Connected", @"已连接");
            }else {
                cell.subTitleLB.textColor = COLOR_TOPIC_SELECT;
                cell.subTitleLB.text = CycLocalizedString(@"Connect", @"连接");
            }
        }else {
            DeviceModel *model = self.userDevices[indexPath.row];
            cell.titleLB.text = model.name;
            if([connectedName isEqualToString:model.name]){
                cell.subTitleLB.textColor = COLOR_NOT_SELECT;
                cell.subTitleLB.text = CycLocalizedString(@"Connected", @"已连接");
            }else {
                cell.subTitleLB.textColor = COLOR_TOPIC_SELECT;
                cell.subTitleLB.text = CycLocalizedString(@"Connect", @"连接");
            }
        }
        
        return cell;
    }
}

#pragma mark ==== delegate代理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 3){
        
        CBPeripheral *peripheral = self.scanDevices[indexPath.row];
        [[CycBLEManager sharedManager] connectPeripheral:peripheral success:^(CBPeripheral *peripheral) {
            NSLog(@"======= 连接成功");
            CycCarModel *model = [[CycCarModel alloc] initWithPeripheral:peripheral];
//            TestViewController *vc = [[TestViewController alloc] init];
//            vc.car = model;
//            [self.navigationController pushViewController:vc animated:YES];
            
            [DeviceRequest bindingDeviceWithSn:model.mac name:model.bleName model:model.model result:^(BOOL ret) {
                NSDictionary *parm = @{
                                       @"flag":@"绑定设备",
                                       @"content":[NSString stringWithFormat:@"绑定设备：%d",ret]
                                       };
                NSString *url = [NSString stringWithFormat:@"%@%@",BaseUrl,Cyc_API_Test];
                [BaseRequest baseGET_New:url cache:NO autoHideLoading:NO parms:parm request:^(id  _Nullable resultObject, NSError * _Nullable error) {
                    
                }];
                if(ret){
                    [self showSuccessWithText:@"绑定成功"];
                }else {
                    [self showErrorWithText:@"绑定失败"];
                }
                if(self.isFirst){
                    [self skipBtnAction];
                }else {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
            }];

        } failure:^(NSError *error) {
            NSLog(@"======= 连接失败");
            [self showErrorWithText:@"连接失败"];
            if(self.isFirst){
                [self skipBtnAction];
            }
        }];
    }
    
    if(indexPath.section == 2){
        DeviceModel *model = self.userDevices[indexPath.row];
        // 判断蓝牙连接状态
        if(![CycBLEManager sharedManager].connected){
            [[CycBLEManager sharedManager] scanAndConnectDeviceWithBleName:model.name success:^(CBPeripheral *peripheral) {
                NSString *url = [NSString stringWithFormat:@"%@%@",BaseUrl,Cyc_API_Test];

                NSDictionary *parm = @{
                                       @"flag":@"蓝牙连接成功*",
                                       @"content":model.name
                                       };

                [BaseRequest baseGET_New:url cache:NO autoHideLoading:NO parms:parm request:^(id  _Nullable resultObject, NSError * _Nullable error) {
                    
                }];
                [self.navigationController popToRootViewControllerAnimated:YES];
            } failure:^(NSError *error) {
                NSString *url = [NSString stringWithFormat:@"%@%@",BaseUrl,Cyc_API_Test];

                NSDictionary *parm = @{
                                       @"flag":@"蓝牙连接失败*",
                                       @"content":model.name
                                       };

                [BaseRequest baseGET_New:url cache:NO autoHideLoading:NO parms:parm request:^(id  _Nullable resultObject, NSError * _Nullable error) {
                    
                }];
                [self showErrorWithText:@"连接失败"];
            }];
        }
    }

}


@end
